package CSDN;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 王圆豪
 * Date: 2025-05-22
 * Time: 13:47
 */

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable = null;
    private long time;

    public MyTimerTask(Runnable runnable,long time){
        this.runnable = runnable;
        this.time = time;
    }

    public Runnable getRunnable(){
        return this.runnable;
    }

    public long getTime(){
        return this.time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer{
    private PriorityQueue<MyTimerTask> q = new PriorityQueue<>();

    private Object locker = new Object();

    public  MyTimer(){
        Thread t = new Thread(()->{
            while (true) {
                synchronized (locker) {
                    try {
                        while (q.isEmpty()) {
                            locker.wait();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    MyTimerTask tmp = q.peek();
                    if (System.currentTimeMillis() < tmp.getTime()){
                        try {
                            locker.wait(tmp.getTime()-System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        tmp.getRunnable().run();
                        q.poll();
                    }
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable, int time){
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable,time + System.currentTimeMillis());
            q.add(myTimerTask);
            locker.notify();
        }
    }
}


public class Test27 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
    }
}
